<?php
//Config
require_once( 'conf/config.php' );
require_once( 'conf/rewriteRules.php' );

if( isset( $_REQUEST['stepNumber'] ) ){
	if( !preg_match( '/\d+/', $_REQUEST['stepNumber'] ) ){
		_returnError( '[ERROR CODE 01] Undefined step number error' );
	}
	//Installation step execution switch
	switch( $_REQUEST['stepNumber'] ){
		case '1':
			_createDB( );
			break;
		case '2':
			_returnDone( 'CDN successfully configured' );
			break;
		case '3':
			_createSuperAdminAccount( );
			break;		
		case '4':
			_setAsInstalled( );
			break;
		default:
			_returnError( '[ERROR CODE 02] Step number error' );
	}
}

//Sets up the database tables
function _createDB( ){
	//Uses global configuration
	global $_CONF;
	//Creates a test connection instance
	@$_mysqli = new mysqli( $_REQUEST['host'], $_REQUEST['user'], $_REQUEST['password'], $_REQUEST['schema'] );
	//Connection error
	if ( mysqli_connect_error( ) ){
		_returnError( '[ERROR CODE 03] Database not found' );
	}
	//Connection charset configuration
	if( !$_mysqli->set_charset( $_CONF['db']['charset'] ) ){
		_returnError( '[ERROR CODE 03] Database not found' );
	};
	//DB config
	file_put_contents( 'conf/dbconfig.php', str_replace( array( '<%host%>','<%port%>','<%schema%>','<%user%>','<%password%>' ), array(  $_REQUEST['host'], $_REQUEST['port'], $_REQUEST['schema'], $_REQUEST['user'], $_REQUEST['password'] ), file_get_contents( 'conf/dbconfig.tpl' ) ) );
	
	//Creates log table
	$_sql_create_log_table =
	"
		CREATE TABLE IF NOT EXISTS `{$_CONF['db']['sys_prefix']}logs`
		(
			`id` INT(9) NOT NULL AUTO_INCREMENT PRIMARY KEY,
			`type` INT(1) UNSIGNED NOT NULL,
			`message` VARCHAR(256) NOT NULL,
			`user` INT(6),
			`action` VARCHAR(256),			
			`time` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
        ) 
		ENGINE=InnoDB DEFAULT CHARSET={$_CONF['db']['charset']}
	";
	
	$_rs = $_mysqli->query( $_sql_create_log_table );
	
	if( !$_rs ){
		_returnError( '[ERROR CODE 04] Systme table [logs] creation error: ' .mysqli_error( $_mysqli ) ."\n QUERY: ". $_sql_create_log_table );
	}
	
	//Creates users table
	$_sql_create_users_table =
	"
		CREATE TABLE IF NOT EXISTS `{$_CONF['db']['sys_prefix']}users`
		(
			`id` INT(6) NOT NULL AUTO_INCREMENT PRIMARY KEY,
			`username` VARCHAR(18) NOT NULL UNIQUE,
			`password` VARCHAR(40) NOT NULL,
			`creation` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
			`status` INT(1) UNSIGNED NOT NULL
        ) 
		ENGINE=InnoDB DEFAULT CHARSET={$_CONF['db']['charset']}
	";
	
	$_rs = $_mysqli->query( $_sql_create_users_table );
	
	if( !$_rs ){
		_returnError( '[ERROR CODE 04] Systme table [users] creation error: ' .mysqli_error( $_mysqli ) ."\n QUERY: ". $_sql_create_users_table );
	}
	
	//Creates user groups table
	$_sql_create_user_groups_table =
	"
		CREATE TABLE IF NOT EXISTS `{$_CONF['db']['sys_prefix']}user_groups`
		(
			`id` INT(6) NOT NULL AUTO_INCREMENT PRIMARY KEY,
			`label` VARCHAR(18) NOT NULL UNIQUE,
			`creation` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
        ) 
		ENGINE=InnoDB DEFAULT CHARSET={$_CONF['db']['charset']}
	";
	
	$_rs = $_mysqli->query( $_sql_create_user_groups_table );
	
	if( !$_rs ){
		_returnError( '[ERROR CODE 04] Systme table [user_groups] creation error: ' .mysqli_error( $_mysqli ) ."\n QUERY: ". $_sql_create_user_groups_table );
	}
	
	//Creates user permissions table
	$_sql_create_user_permissions_table =
	"
		CREATE TABLE IF NOT EXISTS `{$_CONF['db']['sys_prefix']}user_permissions`
		(
			`id` INT(6) NOT NULL AUTO_INCREMENT PRIMARY KEY,
			`label` VARCHAR(64) NOT NULL UNIQUE,
			`creation` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
        ) 
		ENGINE=InnoDB DEFAULT CHARSET={$_CONF['db']['charset']}
	";
	
	$_rs = $_mysqli->query( $_sql_create_user_permissions_table );
	
	if( !$_rs ){
		_returnError( '[ERROR CODE 04] Systme table [user_permissions] creation error: ' .mysqli_error( $_rs ) ."\n QUERY: ". $_sql_create_user_permissions_table );
	}
	
	//Creates user_permissions x user_groups table
	$_sql_create_user_permissions_table_user_groups =
	"
		CREATE TABLE IF NOT EXISTS `{$_CONF['db']['sys_prefix']}user_permissions_user_groups`
		(
			`id` INT(6) NOT NULL AUTO_INCREMENT PRIMARY KEY,
			`permission_id` INT(6) UNSIGNED NOT NULL,
			`user_group_id` INT(6) UNSIGNED NOT NULL,
			`association` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
        ) 
		ENGINE=InnoDB DEFAULT CHARSET={$_CONF['db']['charset']}
	";
	
	$_rs = $_mysqli->query( $_sql_create_user_permissions_table_user_groups );
	
	if( !$_rs ){
		echo $_sql_create_user_permissions_table_user_groups;
		//_returnError( '[ERROR CODE 04] Systme table [user_permissions_user_groups] creation error: ' .mysqli_error( $_rs ) ."\n QUERY: ". $_sql_create_user_permissions_table_user_groups );
	}
	
	//Creates users x user_groups table
	$_sql_create_users_user_groups =
	"
		CREATE TABLE IF NOT EXISTS `{$_CONF['db']['sys_prefix']}user_user_groups`
		(
			`id` INT(6) NOT NULL AUTO_INCREMENT PRIMARY KEY,
			`user_id` INT(6) UNSIGNED NOT NULL,
			`user_group_id` INT(6) UNSIGNED NOT NULL,
			`association` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
        ) 
		ENGINE=InnoDB DEFAULT CHARSET={$_CONF['db']['charset']}
	";
	
	$_rs = $_mysqli->query( $_sql_create_users_user_groups );
	
	if( !$_rs ){
		_returnError( '[ERROR CODE 04] Systme table [user_user_groups] creation error: ' .mysqli_error( $_rs ) ."\n QUERY: ". $_sql_create_users_user_groups );
	}
	
	//Creates query_performance table
	$_sql_create_query_performance =
	"
		CREATE TABLE IF NOT EXISTS `{$_CONF['db']['sys_prefix']}query_performance`
		(
			`id` VARCHAR(6) NOT NULL PRIMARY KEY,
			`sql` VARCHAR(512) NOT NULL,
			`sql_sha1` VARCHAR( 40 ) NOT NULL UNIQUE,
			`avg_time_millis` INT(8) UNSIGNED NOT NULL,
			`times` INT( 8 ) UNSIGNED DEFAULT 0,
			`last_exec` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
        ) 
		ENGINE=InnoDB DEFAULT CHARSET={$_CONF['db']['charset']}
	";
	
	$_rs = $_mysqli->query( $_sql_create_query_performance );
	
	if( !$_rs ){
		_returnError( '[ERROR CODE 04] Systme table [query_performance] creation error: ' .mysqli_error( $_rs ) ."\n QUERY: ". $_sql_create_query_performance );
	}
	
	//Creates the system strings (translations) table
	$_sql_create_strings_table =
	"
		CREATE TABLE IF NOT EXISTS `{$_CONF['db']['sys_prefix']}strings`
		(
			`id` INT(6) NOT NULL AUTO_INCREMENT PRIMARY KEY,
			`label` VARCHAR(128) NOT NULL UNIQUE,
			`creation` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
			`en` VARCHAR(256),
			`es` VARCHAR(256),
			`fr` VARCHAR(256),
			`de` VARCHAR(256),
			`pt` VARCHAR(256),
			`it` VARCHAR(256),
			`cn` VARCHAR(256),
			`ar` VARCHAR(256),
			`nl` VARCHAR(256),
			`ru` VARCHAR(256),
			`pl` VARCHAR(256),
			`jp` VARCHAR(256),
			`in` VARCHAR(256)
        ) 
		ENGINE=InnoDB DEFAULT CHARSET={$_CONF['db']['charset']}
	";
	
	$_rs = $_mysqli->query( $_sql_create_strings_table );
	
	if( !$_rs ){
		_returnError( '[ERROR CODE 04] Systme table [strings] creation error: ' .mysqli_error( $_mysqli ) ."\n QUERY: ". $_sql_create_strings_table );
	}
	
	//Creates the system strings (translations) table
	$_sql_create_user_defined_strings_table =
	"
		CREATE TABLE IF NOT EXISTS `strings`
		(
			`id` INT(6) NOT NULL AUTO_INCREMENT PRIMARY KEY,
			`label` VARCHAR(128) NOT NULL UNIQUE,
			`creation` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
        ) 
		ENGINE=InnoDB DEFAULT CHARSET={$_CONF['db']['charset']}
	";
	
	$_rs = $_mysqli->query( $_sql_create_user_defined_strings_table );
	
	if( !$_rs ){
		_returnError( '[ERROR CODE 04] Systme table [strings] creation error: ' .mysqli_error( $_mysqli ) ."\n QUERY: ". $_sql_create_user_defined_strings_table );
	}
	
	_returnDone( 'Database successfully created' );
}

//Creates the administrator account
function _createSuperAdminAccount( ){
	//Uses global conf
	global $_CONF;
	//db configuration
	require_once( 'conf/dbconfig.php' );
	
	//Password and username retrieveral
	$_username = $_REQUEST['username'];
	$_password = sha1( $_REQUEST['password'] );
	
	//Creates a test connection instance
	@$_mysqli = new mysqli( $_CONF['db']['host'],  $_CONF['db']['username'],  $_CONF['db']['password'],  $_CONF['db']['schema'] );
	//Connection error
	if ( mysqli_connect_error( ) ){
		_returnError( '[ERROR CODE 03] Database not found' );
	}
	//Connection charset configuration
	if( !$_mysqli->set_charset( $_CONF['db']['charset'] ) ){
		_returnError( '[ERROR CODE 03] Database not found' );
	};
	
	//Admin group creation
	$_sql_create_super_admin_group = 
	"
		INSERT INTO `{$_CONF['db']['sys_prefix']}user_groups`
			( label )
				VALUES ( 'superadmin' ) 
	";
	
	$_rs = $_mysqli->query( $_sql_create_super_admin_group );
	
	$_group_id = $_mysqli->insert_id;
	
	if( !$_rs ){
		_returnError( '[ERROR CODE 05] Super admin user group creation error: ' .mysqli_error( $_mysqli ) ."\n QUERY: ". $_sql_create_super_admin_group );
	}
	
	//Do all permission creation
	$_sql_create_super_admin_permission ="
		INSERT INTO `{$_CONF['db']['sys_prefix']}user_permissions`
			( label )
				VALUES ( 'do_all' ) 
	";
	
	$_rs = $_mysqli->query( $_sql_create_super_admin_permission );
	
	$_permission_id = $_mysqli->insert_id;
	
	if( !$_rs ){
		_returnError( '[ERROR CODE 05] Super admin user permission creation error: ' .mysqli_error( $_mysqli ) ."\n QUERY: ". $_sql_create_super_admin_permission );
	}
	
	//Administrator account creation
	$_sql_create_super_admin_user =
	"
		INSERT INTO `{$_CONF['db']['sys_prefix']}users`
			( username, password )
				VALUES ( '{$_username}' , '{$_password}' )		
	";
	
	$_rs = $_mysqli->query( $_sql_create_super_admin_user );
	
	$_user_id = $_mysqli->insert_id;
	
	if( !$_rs ){
		_returnError( '[ERROR CODE 05] Super admin user creation error: ' .mysqli_error( $_mysqli ) ."\n QUERY: ". $_sql_create_super_admin_user );
	}
	
	//Admimistrator user group do_all permission grant
	$_sql_grant_superadmin_all_permissions =
	"
		INSERT INTO `{$_CONF['db']['sys_prefix']}user_permissions_user_groups`
			( permission_id, user_group_id )
				VALUES ( '{$_permission_id}' , '{$_group_id}' )		
	";
	
	$_rs = $_mysqli->query( $_sql_grant_superadmin_all_permissions );
	
	if( !$_rs ){
		_returnError( '[ERROR CODE 05] Superadmin group do all permission granting error: ' .mysqli_error( $_mysqli ) ."\n QUERY: ". $_sql_grant_superadmin_all_permissions );
	}
	
	//Adding administrator to superadming user group
	$_sql_insert_admin_into_superadmin_user_group =
	"
		INSERT INTO `{$_CONF['db']['sys_prefix']}user_user_groups`
			( user_id, user_group_id )
				VALUES ( '{$_user_id}' , '{$_group_id}' )		
	";
	
	$_rs = $_mysqli->query( $_sql_insert_admin_into_superadmin_user_group );
	
	if( !$_rs ){
		_returnError( '[ERROR CODE 05] Admin supearadmin group inclusion error: ' .mysqli_error( $_mysqli ) ."\n QUERY: ". $_sql_insert_admin_into_superadmin_user_group );
	}
	
	 //Everything is going to be all right
	_returnDone( 'Super administrator account successfully created' );
}

//Changes the configuration file to set it as installed
function _setAsInstalled( ){
	file_put_contents( 'conf/status.js' , '{installed:true,mantainance:false}' );
	_returnDone( 'The End' );
}

//Functions
function _returnError( $message ){
	$_res = array( );
	$_res['status'] = 'ko';
	$_res['msg'] = $message;
	echo json_encode( $_res );
	exit;
}

function _returnDone( $msg = '' ){
	$_res = array( );
	$_res['status'] = 'ok';
	$_res['msg'] = $msg;
	echo json_encode( $_res );
	exit;
}

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> 
<html>
	<head>
		<title>{#step_number}) {#step_name}</title>
		<style type="text/css" media="screen">
		label{ width: 140px; float: left; margin-top: 5px; line-height: 21px; height: 21px; font-size: 13px; font-weight: bold; }
		input{ float: left; margin-top: 5px; line-height: 21px; height: 21px; font-size: 13px; }
		br{ clear: both; height: 0px; line-height: 0px;}
		</style>
	</head>
	<body>
	<h1 id="stepTitle"></h1>
	<hr/>
	<form name="step" action="install.php" method="post">
		<input type="hidden" id="stepNumber" value="1"/>
		<div id="stepFields">
		</div>
		<br/>
		<button id="proceed" type="button" style="cursor: pointer;">Proceed &raquo;</button>
		<br/>
	</form>
	<hr/>
	<script type="text/javascript" src="<?php echo $_CONF['paths']['base_url'] . 'static/local/install.js' ?>"></script>
	</body>
</html>